package com.demo.convert;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URL;

/**
 * @author fenggang.li
 * @create 2019-09-10 18:06
 */
@Slf4j
public class BuildOutputFolderAssistant {
    public static void main(String[] args) {
        log.info(getDistFolder("/sub/abc\\\\asdf/"));
    }

    /**
     * 获取maven的默认输出目录target
     *
     * @return
     */
    public static String getBuildOutputFolder() {
        URL resource = BuildOutputFolderAssistant.class.getResource("/");
        String rootFolder = resource.getFile();
        String targetStr = "build/";
        int targetPosition = rootFolder.lastIndexOf(targetStr);
        if (targetPosition == -1) {
            throw new RuntimeException("Build output folder not exist.");
        }
        String targetFolder = rootFolder.substring(0, targetPosition + targetStr.length());
        log.info("targetFolder: " + targetFolder);
        return targetFolder;
    }

    /**
     * 获取target目录下的子目录
     *
     * @param subFolder
     * @return
     */
    public static String getDistFolder(String subFolder) {
        String targetFolder = getBuildOutputFolder();
        String baseFodler = targetFolder + subFolder + File.separator;
        log.info("baseFodler: {}", baseFodler);
        String folderWithoutBackSlash = baseFodler.replaceAll("\\\\", "/");
        log.info("folderWithoutBackSlash: {}", folderWithoutBackSlash);
        String distFolder = folderWithoutBackSlash.replaceAll("//", "/");
        log.info("distFolder: {}", distFolder);
        return distFolder;
    }
}
